<!-- 页面路由配置 -->
<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '我要换油',
    navigationStyle: 'custom',
    disableScroll: true, // 微信禁止页面滚动
    'app-plus': {
      bounce: 'none', // 禁用 iOS 弹性效果
    },
  },
}
</route>

<!-- 页面模板 -->
<template>
  <PageLayout navTitle="我要换油" backRouteName="index" routeMethod="pushTab">
    <!-- 滚动区域 -->
    <scroll-view class="scrollArea" scroll-y>
      <!-- 表单容器 -->
      <view class="form-container">
        <wd-form ref="form" :model="formData">
          <wd-cell-group border:true class="common-form">
            <!-- 原料类型选择器 -->
            <view class="form-item">
              <wd-select-picker
                label="原料类型"
                label-width="100px"
                type="radio"
                prop="materialType"
                v-model="formData.materialType"
                :columns="materialTypes"
                title="请选择原料类型"
                :safe-area-inset-bottom="false"
                :rules="[{ required: true, message: '请选择原料类型' }]"
              ></wd-select-picker>
            </view>

            <!-- 预估重量输入框 -->
            <view class="form-item">
              <wd-input
                label="预估重量"
                label-width="100px"
                prop="estimatedWeight"
                v-model="formData.estimatedWeight"
                :rules="[
                  { required: true, message: '请填写预估重量' },
                  { required: true, pattern: /^\d+$/, message: '只能输入数字' },
                  {
                    required: true,
                    validator: (value) => value >= 0 && value <= 9999999,
                    message: '范围：0-9999999',
                  },
                ]"
                type="number"
              >
                <template #suffix>单位：kg</template>
              </wd-input>
            </view>

            <!-- 联系方式输入框 -->
            <view class="form-item">
              <wd-input
                label="联系方式"
                label-width="100px"
                prop="mob"
                v-model="formData.mob"
                :rules="[
                  { required: true, message: '请填写联系方式' },
                  { required: true, pattern: /^\d+$/, message: '只能输入数字，请重新输入' },
                  { required: true, validator: validatePhone, message: '请输入有效的手机号' },
                ]"
                placeholder="请输入联系方式"
                @blur="validatePhone"
              >
                <template #extra>
                  <view class="phone-tip" v-if="showPhoneTip">只能输入数字，请重新输入</view>
                </template>
                <template #suffix>
                  <button
                    class="custom-phone-button"
                    open-type="getPhoneNumber"
                    @getphonenumber="getPhoneNumber"
                    style="margin-left: 10px"
                  >
                    获取微信手机号
                  </button>
                </template>
              </wd-input>
            </view>
            <view class="form-item">
              <wd-input
                prefix-icon="location"
                label="地址"
                label-width="100px"
                placeholder="请输入或选择地址"
                v-model="formData.address"
              >
                <template #suffix>
                  <button
                    class="custom-phone-button"
                    @click="goToLocationPage"
                    style="margin-left: 10px"
                  >
                    选择地址
                  </button>
                </template>
              </wd-input>
            </view>
            <!-- 备注输入框 -->
            <view class="form-item">
              <wd-textarea
                label="备注"
                label-width="100px"
                prop="comments"
                v-model="formData.comments"
                :rules="[{ required: true, max: 1000, message: '备注最多只能输入1000个字符' }]"
                :maxlength="1000"
                show-word-limit
                placeholder="请输入备注"
              ></wd-textarea>
            </view>

            <!-- 已阅读并同意《换油须知》选项 -->
            <!-- <view class="agreement-container">
              <wd-checkbox
                v-model="formData.agreedToTerms"
                prop="agreedToTerms"
                :rules="[{ validator: (value) => value === '111', message: '请选中已阅读并同意' }]"
              >
                已阅读并同意
              </wd-checkbox>
              <wd-text
                type="primary"
                class="agreement-link"
                @click="openTermsDocument"
                text="《换油须知》"
              ></wd-text>
            </view> -->
          </wd-cell-group>
        </wd-form>
      </view>
      <view class="konw-and-agree">
        <wd-checkbox checked-color="#01b43f" v-model="formData.agreedToTerms" @change="handleknow">
          已阅读并同意换油须知
        </wd-checkbox>
      </view>
    </scroll-view>

    <!-- 底部按钮区域 -->
    <view class="footer">
      <wd-button class="submit-form" block @click="handleSubmit">提交</wd-button>
      <wd-button class="hold-form" block type="success" @click="handleStaging">暂存</wd-button>
    </view>
  </PageLayout>
</template>

<!-- 脚本部分 -->
<script lang="ts" setup>
import { useToast, useMessage, useNotify } from 'wot-design-uni'
import { useRouter } from '@/plugin/uni-mini-router'
import { useUserStore } from '@/store/user'
import { http } from '@/utils/http'
import { orderApi, userApi } from '@/api/api'
import { ref, reactive } from 'vue'
import { debounce } from 'lodash'
import { useLocationStore } from '@/store/location'
import { materialTypes } from '@/common/constants'

// 组件选项配置
defineOptions({
  name: 'ExchangeCreateOrder',
  options: {
    styleIsolation: 'shared',
  },
})

// 初始化工具和状态
const toast = useToast()
const router = useRouter()
const userStore = useUserStore()
const locationStore = useLocationStore()
const value = ref<boolean>(true)

// 表单数据
const formData = reactive({
  materialType: 'A',
  estimatedWeight: '',
  mob: userStore.userInfo.phone,
  address: '',
  comments: '',
  agreedToTerms: false, // 是否同意《换油须知》
})

// 表单引用
const form = ref(null)

// 初始化时从store加载地址
if (locationStore.selectedLocation) {
  formData.address = locationStore.selectedLocation.address
}
// 监听位置变化
const unsubscribe = locationStore.$subscribe((mutation, state) => {
  if (state.selectedLocation) {
    formData.address = state.selectedLocation.address
  }
})

// 提交表单处理
const handleSubmit = debounce(
  async () => {
    form.value
      .validate()
      .then(async ({ valid, errors }) => {
        if (valid) {
          if (formData.agreedToTerms !== true) {
            toast.error('请阅读并同意《换油须知》')
            return
          }
          console.log('表单校验通过，提交数据:', formData)
          const res = await http.post(orderApi.exchangeCreateOrder, { ...formData, status: 'B' })
          if (res.success) {
            toast.success('保存成功')
            handleSuccess()
          } else {
            toast.error(res?.message || '表单保存失败！')
          }
        }
      })
      .catch((error) => {
        console.error('表单校验失败:', error)
        uni.showToast({
          title: '请检查表单内容',
          icon: 'none',
        })
      })
  },
  1000,
  { leading: true, trailing: false },
)

// 暂存表单处理
const handleStaging = debounce(
  async () => {
    const res = await http.post(orderApi.exchangeCreateOrder, { ...formData, status: 'A' })
    if (res.success) {
      toast.success('暂存成功')
      handleSuccess()
    } else {
      toast.error(res?.message || '暂存失败！')
    }
  },
  1000,
  { leading: true, trailing: false },
)

// 手机号验证状态
const showPhoneTip = ref(false)

// 手机号验证方法
const validatePhone = (value) => {
  showPhoneTip.value = !/^\d+$/.test(value)
  return /^1[3-9]\d{9}$/.test(value)
}

// 打开《换油须知》文档
const openTermsDocument = () => {
  // 这里替换为实际文档的路径或链接
  uni.navigateTo({
    url: '/pages/documents/TermsOfService',
  })
  formData.agreedToTerms = true
}

// 获取微信手机号方法
const getPhoneNumber = async (e: any) => {
  try {
    // #ifdef MP-WEIXIN
    if (e.detail && e.detail.errMsg !== 'getPhoneNumber:ok') {
      throw new Error('用户拒绝了授权')
    }

    const [loginRes, phoneRes] = await Promise.all([
      new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: resolve,
          fail: reject,
        })
      }),
      Promise.resolve(e.detail ? e.detail.code : null),
    ])

    const params = {
      code: phoneRes,
    }

    const res = await http.post(userApi.getUserPhoneByWx, params)

    if (res.success) {
      // 将获取到的手机号填入表单
      formData.mob = res.result as string
    } else {
      throw new Error(res.message || '获取手机号失败')
    }
    // #endif
    // #ifndef MP-WEIXIN
    // 非微信环境模拟数据
    console.log('现在使用的是非微信环境')
    formData.mob = '13272408547'
    // #endif
  } catch (err: any) {
    toast.warning(err.message || '获取手机号失败')
  }
}

// 跳转到地图选择页面
const goToLocationPage = () => {
  if (locationStore.selectedLocation) {
    locationStore.setTempLocation(locationStore.selectedLocation)
  }

  uni.navigateTo({
    url: '/pages-user/location/location',
  })
}

// 同意协议
const handleknow = (e) => {
  value.value = e.value
}

const handleSuccess = () => {
  uni.$emit('refreshList')
  router.back()
}

onUnmounted(() => {
  unsubscribe()
})
</script>
<style lang="scss" scoped>
@import '@/style/custom/variables.scss';
.footer {
  padding: 10px 15px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  gap: 5px;
  :deep(.wd-button) {
    flex: 1;
  }
}
/* 添加获取手机号按钮样式 */
.custom-phone-button {
  // margin-left: 10px;
  // background: transparent; /* 透明背景 */
  display: inline-flex;
  padding: 0 8px; /* 内边距 */
  height: 28px; /* 高度匹配 wd-button */
  line-height: 28px;
  font-size: 12px; /* 字体大小 */
  color: #333; /* 文字颜色 */
  // border: 1px solid #ddd; /* 边框 */
  // border-radius: 4px; /* 圆角 */
}

/* 如果需要 hover 效果 */
.custom-phone-button:hover {
  opacity: 0.8;
}

// 统一样式
.common-form {
  background: none;
  .form-item {
    background: white;
    margin: 30upx 20upx;
    // box-shadow: 0 2upx 20upx #000;
    // border-radius: 20upx;
    // border: 4upx solid $primary-color; // 使用 SCSS 变量
    :deep(.wd-input) {
      background: none;
    }

    :deep(.wd-select-picker__cell) {
      background: none;
    }
  }
}
:deep(.wd-cell-group__body) {
  background: none;
}
:deep(.wd-textarea) {
  margin: 30upx 20upx;
  border-radius: 30upx;
  // background: none;
}

.footer {
  margin-bottom: 50upx;
}

.footer:deep(.wd-button) {
  border-radius: 40upx !important;
}
.submit-form {
  background: $primary-color !important; // 使用 SCSS 变量
}
.hold-form {
  background: #333333 !important;
}

.konw-and-agree {
  display: flex;
  align-items: center;
  justify-content: center;
  // color: $primary-color; // 使用 SCSS 变量
  :deep(.wd-checkbox__txt) {
    color: $primary-color; // 使用 SCSS 变量
  }
}
</style>
